package com.lxw.manage_cms.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lxw.framework.domain.cms.CmsPage;
import com.lxw.framework.domain.cms.CmsTemplate;
import com.lxw.framework.domain.cms.request.QueryPageRequest;
import com.lxw.framework.domain.cms.response.CmsCode;
import com.lxw.framework.exception.CustomException;
import com.lxw.framework.model.response.CommonCode;
import com.lxw.manage_cms.config.CmsConfiguration;
import com.lxw.manage_cms.dao.CmsPageDao;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class CmsPageServiceImpl implements ICmsPageService{

    @Autowired
    CmsPageDao cmsPageDao;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    ICmsGridFsService iCmsGridFsService;
    @Autowired
    ICmsTemplateService cmsTemplateService;


    @Override
    public Page<CmsPage> findList(Integer page, Integer pageSize, QueryPageRequest qpr) {

        //设置查询条件参数 siteId templateId 准确查询， Aliase模糊查询
        CmsPage cmsPage = new CmsPage();
        if (StringUtils.isNotEmpty(qpr.getSiteId())){
            cmsPage.setSiteId(qpr.getSiteId());
        }
        if (StringUtils.isNotEmpty(qpr.getTemplateId())){
            cmsPage.setTemplateId(qpr.getTemplateId());
        }
        if (StringUtils.isNotEmpty(qpr.getPageAliase())){
            cmsPage.setPageAliase(qpr.getPageAliase());
        }
        //设置模糊查询
        //条件匹配器
        ExampleMatcher exampleMatcher = ExampleMatcher.matching();
        exampleMatcher = exampleMatcher.withMatcher("pageAliase",
                ExampleMatcher.GenericPropertyMatchers.contains());
        //创建条件实例
        Example<CmsPage> of = Example.of(cmsPage, exampleMatcher);

        //PageRequest 用做分页查询的封装页码数的参数类
        page -= 1;
        PageRequest of2 = PageRequest.of(page, pageSize);
        Page<CmsPage> all = cmsPageDao.findAll(of,of2);


        return all;
    }

    @Override
    public CmsPage add(CmsPage cmsPage) {
        //创建页面名称、站点Id、页面webpath为唯一索引
        //1. 校验唯一索引
        CmsPage cmsPage1 = new CmsPage();
        cmsPage1.setPageName(cmsPage.getPageName());
        cmsPage1.setSiteId(cmsPage.getSiteId());
        cmsPage1.setPageWebPath(cmsPage1.getPageWebPath());
        //创建条件实例
        Example<CmsPage> of = Example.of(cmsPage1);

        long count = cmsPageDao.count(of);
        if (count > 0){
            //代表已经存在 不能保存创建
            throw new RuntimeException("页面名称、站点Id、页面webpath为唯一索引");
        }

        //保存页面信息
        CmsPage save = cmsPageDao.save(cmsPage);


        return save;
    }

    @Override
    public CmsPage findById(String pageId) {

        //通过ID查询页面信息
        Optional<CmsPage> byId = cmsPageDao.findById(pageId);
        if (byId.isPresent()){
            return byId.get();
        }


        return null;
    }

    @Override
    public CmsPage savePage(CmsPage cmsPage) {
        //更新页面信息
        if (StringUtils.isEmpty(cmsPage.getPageId())){
            throw new RuntimeException("pageID为空");
        }
        //1.先通过Id查询
        String pageId = cmsPage.getPageId();
        Optional<CmsPage> byId = cmsPageDao.findById(pageId);
        if (!byId.isPresent()){
            //如果结果为空
            throw new RuntimeException("此ID不存在");
        }
        CmsPage cmsPage1 = byId.get();

        //非空判断
        // // 2更新 （注意：必选判断非空和空字符）
        if (StringUtils.isNotEmpty(cmsPage.getSiteId())){
            cmsPage1.setSiteId(cmsPage.getSiteId());
        }
        if (StringUtils.isNotEmpty(cmsPage.getTemplateId())){
            cmsPage1.setTemplateId(cmsPage.getTemplateId());
        }

        if (StringUtils.isNotEmpty(cmsPage.getPageName())){
            cmsPage1.setPageName(cmsPage.getPageName());
        }

        if (StringUtils.isNotEmpty(cmsPage.getPageAliase())){
            cmsPage1.setPageAliase(cmsPage.getPageAliase());
        }
        if (StringUtils.isNotEmpty(cmsPage.getPageWebPath())){
            cmsPage1.setPageWebPath(cmsPage.getPageWebPath());
        }
        if (StringUtils.isNotEmpty(cmsPage.getPagePhysicalPath())){
            cmsPage1.setPagePhysicalPath(cmsPage.getPagePhysicalPath());
        }

        if (StringUtils.isNotEmpty(cmsPage.getPageType())){
            cmsPage1.setPageType(cmsPage.getPageType());
        }

        if (StringUtils.isNotEmpty(cmsPage.getDataUrl())){
            cmsPage1.setDataUrl(cmsPage.getDataUrl());
        }


        //创建页面名称、站点Id、页面webpath为唯一索引


        CmsPage save = cmsPageDao.save(cmsPage1);

        return save;
    }

    @Override
    public void delPage(String pageId) {

        cmsPageDao.deleteById(pageId);


    }

    @Override
    public void postPage(String pageId) {
        //页面静态化

        //1.获取到页面信息
        Optional<CmsPage> byId = cmsPageDao.findById(pageId);
        if (!byId.isPresent()){
            throw new CustomException(CmsCode.CMS_COURSE_PAGEIDNOTEXISTS);
        }
        CmsPage cmsPage = byId.get();
        //获取页面model
        String dataUrl = cmsPage.getDataUrl();
        String forObject = restTemplate.getForObject(dataUrl, String.class);
        JSONObject jsonObject = JSON.parseObject(forObject);
        Map<String, Object> map = new HashMap<>();
        map.put("obj",jsonObject);

        //获取模板
        String templateId = cmsPage.getTemplateId();
        CmsTemplate template = cmsTemplateService.findTemplateById(templateId);
        String templateFileId = template.getTemplateFileId();
        String tempStr = iCmsGridFsService.queryContentById(templateFileId);
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        String uuid = UUID.randomUUID().toString().replace("-","");
        stringTemplateLoader.putTemplate(uuid,tempStr);
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setURLEscapingCharset("UTF-8");
        configuration.setTemplateLoader(stringTemplateLoader);
        Template template1 = null;
        try {
            template1 = configuration.getTemplate(uuid);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //页面静态化
        String htmlStr = null;
        try {
            htmlStr = FreeMarkerTemplateUtils.processTemplateIntoString(template1, map);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        //将页面储存到GridFs
        try {
            InputStream inputStream = IOUtils.toInputStream(htmlStr, "UTF-8");
            ObjectId fileId = iCmsGridFsService.addTemplate(inputStream, cmsPage.getPageName());
            //更新数据库


            cmsPage.setHtmlFileId(fileId.toString());
            cmsPageDao.save(cmsPage);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(CommonCode.FAIL);
        }

        //通知服务端下载文件--MQ
        String routingKey = cmsPage.getSiteId();
        HashMap<String, Object> msgMap = new HashMap<String, Object>();
        msgMap.put("pageId",pageId);
        //发送到消费端写入到磁盘
        rabbitTemplate.convertAndSend(CmsConfiguration.EXCHANGE_NAME,routingKey,JSON.toJSONString(msgMap));


    }


}
